import { useState, useMemo } from 'react'

type ChildProps = {
  user: { age: number }
}

const Child = ({ user }: ChildProps) => {
  console.log('Child 组件更新')
  return (
    <div style={{ backgroundColor: '#abc', padding: 5 }}>
      子组件 - 年龄： {user.age}
    </div>
  )
}

function UseMemo3 () {
  const [count, setCount] = useState(0)
  const [theme, setTheme] = useState('pink')

  // const user = useMemo(() => {
  //   return { age: count + 20 }
  // }, [count])

  // 使用 useMemo 来记忆组件从而模拟 React.memo 高阶组件的功能：
  const child = useMemo(() => <Child user={{ age: count + 20 }} />, [count])

  return (
    <div style={{ backgroundColor: theme, padding: 10 }}>
      <button onClick={() => setTheme(theme === 'pink' ? 'white' : 'pink')}>
        切换主题
      </button>

      <h1>计数器：{count}</h1>
      <button onClick={() => setCount(count + 1)}>+1</button>

      <hr />
      {/* <Child user={user} /> */}
      {/* 渲染 child，也就是 <Child /> */}
      {child}
    </div>
  )
}

export default UseMemo3
